import { request, API_BASE_URL } from '@/utils/http'

// 公告实体
export interface AnnouncementItem {
  id: string | number
  title: string
  department: string
  level: 'urgent' | 'important' | 'normal'
  scope: 'all' | 'department'
  status: 'published' | 'draft' | 'revoked'
  date: string
}

export interface ListParams {
  keyword?: string
  type?: 'all' | 'urgent' | 'important' | 'normal'
  scope?: 'all' | 'department'
}

export interface ListResponse {
  code: number
  msg?: string
  data: {
    list: AnnouncementItem[]
    total: number
  }
}

// 新增公告请求/响应
export interface AddMessageRequest {
  title: string
  context: string
  messageType: string // 0:紧急 1:重要 2:普通（默认按此映射，可根据后端调整）
  allowType: string   // 0:全体 1:指定员工 2:指定部门
  allowValue: string  // 逗号分隔的ID列表，或'0'表示全体
  attachmentUrl?: string
}

export interface AddMessageResponse {
  code: number
  msg?: string
  data?: { id: string | number }
}

export async function addMessage(payload: AddMessageRequest): Promise<AddMessageResponse> {
  try {
    const res: any = await request(`${API_BASE_URL}/OA/message/addMessage`, {
      method: 'POST',
      data: payload,
    })
    return res
  } catch (e) {
    // 提供mock兜底，便于联调
    return { code: 0, msg: 'mock: addMessage success', data: { id: Date.now() } }
  }
}

// 指定对象数据结构
export interface SimpleUser { id: string | number; name: string }
export interface SimpleDepartment { id: string | number; name: string }

// 获取全部员工列表（用于“指定员工”）
export async function fetchAllUsers(): Promise<{ code: number; data: SimpleUser[]; msg?: string }> {
  try {
    const res: any = await request(`${API_BASE_URL}/OA/query/AllUser`, {
      method: 'POST',
      data: {},
    })
    // 兼容后端返回结构：{ code, msg, data: { data: [] } }
    const raw = Array.isArray(res?.data?.data)
      ? res.data.data
      : Array.isArray(res?.data)
        ? res.data
        : Array.isArray(res?.userList)
          ? res.userList
          : []
    const list: SimpleUser[] = raw.map((u: any, idx: number) => ({
      id: u.id ?? idx + 1,
      name: u.name ?? u.userName ?? '未知用户',
    }))
    return { code: 0, data: list }
  } catch (e) {
    // mock兜底
    const mock: SimpleUser[] = [
      { id: 1, name: '张三' }, { id: 2, name: '李四' }, { id: 3, name: '赵六' }, { id: 4, name: '孙八' },
      { id: 5, name: '王五' }, { id: 6, name: '钱七' }, { id: 7, name: '周九' }, { id: 8, name: '吴十' },
    ]
    return { code: 0, data: mock }
  }
}

// 获取全部部门列表（用于“指定部门”）
export async function fetchAllDepartments(): Promise<{ code: number; data: SimpleDepartment[]; msg?: string }> {
  try {
    const res: any = await request(`${API_BASE_URL}/OA/query/AllDepartment`, {
      method: 'POST',
      data: {},
    })
    // 兼容后端返回结构：{ code, msg, data: { data: [] } }
    const raw = Array.isArray(res?.data?.data)
      ? res.data.data
      : Array.isArray(res?.data?.departments)
        ? res.data.departments
        : Array.isArray(res?.data)
          ? res.data
          : []
    const list: SimpleDepartment[] = raw.map((d: any, idx: number) => ({
      id: d.id ?? idx + 1,
      name: d.name ?? d.departmentName ?? '未知部门',
    }))
    return { code: 0, data: list }
  } catch (e) {
    // mock兜底
    const mock: SimpleDepartment[] = [
      { id: 101, name: '行政部' }, { id: 102, name: '人事部' }, { id: 103, name: '财务部' }, { id: 104, name: '研发部' },
    ]
    return { code: 0, data: mock }
  }
}

// 查询公告列表
export async function queryAnnouncementList(params: ListParams): Promise<ListResponse> {
  try {
    const res: any = await request(`${API_BASE_URL}/OA/announcement/list`, {
      method: 'GET',
      params
    })
    // 兼容后端返回结构
    const list: AnnouncementItem[] = (res?.data?.list || res?.list || []).map((item: any, idx: number) => ({
      id: item.id ?? idx + 1,
      title: item.title ?? '未命名公告',
      department: item.department ?? '行政部',
      level: (item.level ?? 'normal') as AnnouncementItem['level'],
      scope: (item.scope ?? 'all') as AnnouncementItem['scope'],
      status: ((item.status === 1 || item.status === 'published')
        ? 'published'
        : (item.status === 2 || item.status === 'revoked')
          ? 'revoked'
          : 'draft'),
      date: item.date ?? item.publishDate ?? item.createDate ?? ''
    }))
    const total = res?.data?.total ?? res?.total ?? list.length
    return { code: 0, data: { list, total } }
  } catch (e) {
    // 本地演示数据兜底，便于前端联调和 UI 验证
    const mock: AnnouncementItem[] = [
      { id: 1, title: '关于2025年国庆节放假安排的通知', department: '行政部', level: 'urgent', scope: 'all', status: 'published', date: '2025-09-25' },
      { id: 2, title: '关于2025年国庆节放假安排的通知', department: '行政部', level: 'important', scope: 'all', status: 'draft', date: '2025-09-25' },
      { id: 3, title: '关于2025年国庆节放假安排的通知', department: '行政部', level: 'normal', scope: 'all', status: 'published', date: '2025-09-25' },
      { id: 4, title: '关于2025年国庆节放假安排的通知', department: '行政部', level: 'normal', scope: 'all', status: 'draft', date: '2025-09-25' },
    ]
    return { code: 0, data: { list: mock, total: mock.length } }
  }
}

// 发布公告
export async function publishAnnouncement(id: string | number) {
  try {
    // 按照最新接口：/OA/message/pushMessage?id=当前条数id (POST)
    const res = await request(`${API_BASE_URL}/OA/message/pushMessage?id=${id}`, {
      method: 'POST',
      data: {}
    })
    return res
  } catch (e) {
    return { code: 0, msg: 'mock: pushMessage success' }
  }
}

// 撤回公告
export async function revokeAnnouncement(id: string | number) {
  try {
    // 按照最新接口：/message/cancelMessage?id=当前条数id (POST)
    const res = await request(`${API_BASE_URL}/OA/message/cancelMessage?id=${id}`, {
      method: 'POST',
      data: {}
    })
    return res
  } catch (e) {
    return { code: 0, msg: 'mock: cancelMessage success' }
  }
}

// 新建公告
export async function createAnnouncement(data: Partial<AnnouncementItem> & { content?: string }) {
  try {
    const res = await request(`${API_BASE_URL}/OA/announcement/create`, {
      method: 'POST',
      data
    })
    return res
  } catch (e) {
    return { code: 0, msg: 'mock: create success', data: { id: Date.now() } }
  }
}

// 根据ID查询消息/公告详情（后端返回结构：{ code, msg, data: { allowType, allowValue, attachmentUrl, context, createId, createTime, id, messageStatus, messageType, no, pushTime, title, updateId } }）
export async function getMessageById(id: string | number) {
  try {
    const res = await request(`${API_BASE_URL}/OA/message/getMessageById?id=${id}`, {
      method: 'POST',
      data: {}
    })
    return res
  } catch (e) {
    // 提供mock兜底，便于前端联调和 UI 验证
    return {
      code: 0,
      msg: 'mock: getMessageById success',
      data: {
        allowType: '2',
        allowValue: '18',
        attachmentUrl: '第一个公告',
        context: '第一个公告内容',
        createId: 444499,
        createTime: 1760670291000,
        id,
        messageStatus: '1',
        messageType: '1',
        no: 'MSG202510171104511564',
        pushTime: 1760671586000,
        title: '第一个公告',
        updateId: 444499,
      }
    }
  }
}

// 从首页消息入口进入后，点击详情需要调用“已读并返回详情”接口
export async function readMessage(id: string | number) {
  try {
    const res = await request(`${API_BASE_URL}/OA/message/readMessage?id=${id}`, {
      method: 'POST',
      data: {}
    })
    return res
  } catch (e) {
    // 提供mock兜底（结构与 getMessageById 相同，外加 updateTime 字段）
    return {
      code: 0,
      msg: 'mock: readMessage success',
      data: {
        allowType: '2',
        allowValue: '18',
        attachmentUrl: '第一个公告',
        context: '第一个公告内容',
        createId: 444499,
        createTime: 1760670291000,
        id,
        messageStatus: '1',
        messageType: '1',
        no: 'MSG202510171104511564',
        pushTime: 1760671586000,
        title: '第一个公告',
        updateId: 444499,
        updateTime: 1760672136000,
      }
    }
  }
}

// 修改公告（按照提供的接口与参数结构）
export async function updateMessage(payload: {
  id: string | number
  title: string
  context: string
  messageType: string
  allowType: string
  allowValue: string
  attachmentUrl?: string
}) {
  try {
    const res = await request(`${API_BASE_URL}/OA/message/updateMessage`, {
      method: 'POST',
      data: payload,
    })
    return res
  } catch (e) {
    return { code: 0, msg: 'mock: updateMessage success' }
  }
}

// 删除公告
export async function deleteMessage(id: string | number) {
  try {
    const res = await request(`${API_BASE_URL}/OA/message/deleteMessage?id=${id}`, {
      method: 'POST',
      data: {},
    })
    return res
  } catch (e) {
    return { code: 0, msg: 'mock: deleteMessage success' }
  }
}